﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media.Media3D;

namespace OPCService.Utils
{
    public static class Loading
    {
        private static LoadingAnimation _loadingAnimation;
        private static Form _hostForm;

        public static void Show(Form hostForm = null)
        {
            if (_loadingAnimation != null)
                return;

            // 如果未指定窗体，则使用当前活动窗体
            if (hostForm == null && Application.OpenForms.Count > 0)
            {
                hostForm = Application.OpenForms[0];
            }

            if (hostForm == null)
            {
                MessageBox.Show("无法找到可用窗体！");
                return;
            }

            _hostForm = hostForm;

            // 创建并配置加载动画控件
            _loadingAnimation = new LoadingAnimation
            {
                Location = new Point((hostForm.Width - 60) / 2, (hostForm.Height - 60) / 2),
                ForegroundColor = Color.Blue,
                AnimationSpeed = 30
            };

            // 将控件添加到窗体
            hostForm.Controls.Add(_loadingAnimation);
            _loadingAnimation.BringToFront(); // 确保显示在最上层
            _loadingAnimation.Start();
        }

        public static void Hide()
        {
            if (_loadingAnimation == null)
                return;

            // 从窗体中移除控件
            _hostForm?.Controls.Remove(_loadingAnimation);
            _loadingAnimation.Stop();
            _loadingAnimation.Dispose();
            _loadingAnimation = null;
            _hostForm = null;
        }
    }

    // 自定义加载动画控件（与之前相同）
    public class LoadingAnimation : Control
    {
        private Timer _timer;
        private float _angle = 0f;
        private bool _isRunning = false;
        private int _cornerRadius = 10;

        public Color ForegroundColor { get; set; } = Color.Blue;
        public int AnimationSpeed { get; set; } = 30;
        private string _loadingText = "加载中...";

        public int CornerRadius
        {
            get => _cornerRadius;
            set
            {
                _cornerRadius = Math.Max(0, value);
                UpdateRegion();
                Invalidate();
            }
        }

        public string LoadingText
        {
            get => _loadingText;
            set
            {
                _loadingText = value;
                Invalidate(); // 文字变化时重绘
            }
        }

        public LoadingAnimation()
        {
            this.Size = new Size(60, 60);
            this.DoubleBuffered = true;
            this.BackColor = Color.LightBlue;

            _timer = new Timer
            {
                Interval = AnimationSpeed
            };
            _timer.Tick += OnTimerTick;

            this.CornerRadius = 10;
            this.Resize += (s, e) => UpdateRegion();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            if (!_isRunning) return;

            // 使用自定义路径绘制圆角背景
            using (var path = CreateRoundedRectangle(new Rectangle(0, 0, Width, Height), _cornerRadius))
            {
                e.Graphics.FillPath(new SolidBrush(this.BackColor), path);
            }


            DrawLoadingAnimation(e.Graphics);
            //DrawLoadingText(e.Graphics);
        }

        private void DrawLoadingAnimation(Graphics g)
        {
            var center = new Point(Width / 2, Height / 2);
            var radius = Math.Max(10, Math.Min(Width, Height) / 3);

            for (int i = 0; i < 8; i++)
            {
                var angle = _angle + i * 45; // 8 个点，间隔 45°
                var x = center.X + (float)(radius * Math.Sin(angle * Math.PI / 180));
                var y = center.Y + (float)(radius * Math.Cos(angle * Math.PI / 180));

                // 动态缩放：使用不同相位的正弦波
                float scale = (float)(1 + Math.Sin(_angle * Math.PI / 180 + i * 30)) / 2; // 每个点偏移 30° 相位
                float size = Math.Max(4, 16f * scale); // 保证最小值为 4

                // 创建圆形区域
                var rect = new Rectangle(
                    (int)Math.Round(x - size / 2),
                    (int)Math.Round(y - size / 2),
                    (int)Math.Round(size),
                    (int)Math.Round(size)
                );

                // 使用 PathGradientBrush 实现圆形渐变
                using (var path = new GraphicsPath())
                {
                    path.AddEllipse(rect);
                    using (var brush = new PathGradientBrush(path))
                    {
                        Color centerColor = Color.FromArgb(255, ForegroundColor);
                        Color edgeColor = Color.FromArgb(0, ForegroundColor);

                        brush.CenterPoint = new PointF(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
                        brush.SurroundColors = new[] { edgeColor };

                        g.FillPath(brush, path);
                    }
                }
            }
        }

        private GraphicsPath CreateRoundedRectangle(Rectangle bounds, int cornerRadius)
        {
            // 创建 GraphicsPath 对象
            var path = new GraphicsPath();

            // 调整边界，防止圆角半径过大
            int diameter = cornerRadius * 2;
            Rectangle arcRectangle;

            // 左上角圆弧
            arcRectangle = new Rectangle(bounds.Location, new Size(diameter, diameter));
            path.AddArc(arcRectangle, 180, 90); // 左上角圆弧

            // 右上角圆弧
            arcRectangle.X = bounds.Right - diameter;
            path.AddArc(arcRectangle, 270, 90); // 右上角圆弧

            // 右下角圆弧
            arcRectangle.Y = bounds.Bottom - diameter;
            path.AddArc(arcRectangle, 0, 90);   // 右下角圆弧

            // 左下角圆弧
            arcRectangle.X = bounds.Left;
            path.AddArc(arcRectangle, 90, 90);  // 左下角圆弧

            // 闭合路径
            path.CloseFigure();

            return path;
        }

        private void DrawLoadingText(Graphics g)
        {
            if (string.IsNullOrWhiteSpace(LoadingText))
                return;

            // 设置字体和颜色
            var font = new Font("Segoe UI", 10, FontStyle.Regular);
            var brush = new SolidBrush(ForeColor);

            // 计算文字绘制位置
            var textRect = new Rectangle(
                0,
                Height - 40, // 文字距离底部 40px
                Width,
                40
            );

            var format = new StringFormat
            {
                Alignment = StringAlignment.Center, // 水平居中
                LineAlignment = StringAlignment.Center // 垂直居中
            };

            g.DrawString(LoadingText, font, brush, textRect, format);

            font.Dispose();
            brush.Dispose();
        }

        private void OnTimerTick(object sender, EventArgs e)
        {
            _angle -= 4f;
            if (_angle < 0) _angle = 360f;
            this.Invalidate();
        }

        private void UpdateRegion()
        {
            if (_cornerRadius <= 0)
            {
                this.Region = null;
                return;
            }

            using (var path = CreateRoundedRectangle(new Rectangle(0, 0, Width, Height), _cornerRadius))
            {
                this.Region = new Region(path);
            }
        }

        public void Start()
        {
            if (!_isRunning)
            {
                _isRunning = true;
                _timer.Start();
            }
        }

        public void Stop()
        {
            if (_isRunning)
            {
                _isRunning = false;
                _timer.Stop();
                _angle = 0f;
                this.Invalidate();
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _timer?.Stop();
                _timer?.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
